import { Texture2D } from "cc";
import DateUtil from "./DateUtil";
import { EngineConfig } from "./EngineConfig";
import { EventManager } from "./EventManager";
import { Logger } from "./Logger";

export class RemoteAssetManager {

    public static instance: RemoteAssetManager = new RemoteAssetManager()

    public cacheAsset: Map<string, RemoteAsset> = new Map<string, RemoteAsset>()

    private lastCheckTime: number = DateUtil.now()

    private needCheckTime: number = 1000 * 60
    private cacheTime: number = 1000 * 60 * 5


    public init() {
        EventManager.instance.on(EngineConfig.Event_Type.Event_FrameUpdate, this.onFrameUpdate, this);
    }

    private onFrameUpdate(now: number) {
        let passTime: number = now - this.lastCheckTime
        if (passTime >= this.needCheckTime) {
            this.lastCheckTime = now
            let deleteArr: Array<string> = []
            // Logger.log("RemoteAssetManager =-", this.cacheAsset)
            this.cacheAsset.forEach((remoteAsset: RemoteAsset) => {
                let passTime = now - remoteAsset.time
                if (passTime >= this.cacheTime) {
                    // ResourcesManager.instance.releaseAsset(remoteAsset.texture)
                    deleteArr.push(remoteAsset.url)
                    // Logger.log("RemoteAssetManager delete=-", remoteAsset.url, deleteArr)
                }
            });
            for (let i = 0; i < deleteArr.length; i++) {
                this.cacheAsset.delete(deleteArr[i])
            }
        }
    }

    public insertAsset(asset: RemoteAsset) {
        this.cacheAsset.set(asset.url, asset)
    }

}

export class RemoteAsset {

    public url: string;
    public texture: Texture2D
    public time: number;

    constructor(url: string, asset: Texture2D, time: number) {
        this.url = url
        this.texture = asset;
        this.time = time;
    }

}